import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import { createPinia } from 'pinia'
import packageJson from '../../package.json'
import router, { routes } from '@/router/index'
import { useUserStore } from './user'

export const pinia = createPinia()
const LOCALSTORAGEKEY = packageJson.name

// 从 localStorage 获取初始状态
const getLocalState = () => {
  try {
    return JSON.parse(localStorage.getItem(LOCALSTORAGEKEY)) || {}
  } catch (err) {
    return {}
  }
}

export const useSystemStore = defineStore('system', {
  state: () => {
    const savedState = getLocalState();
    return {
      state: savedState,
      token: savedState.token || '',
      permissions: savedState.permissions || [],
      routes: []
    }
  },

  getters: {
    isLogin: (state) => !!state.token
  },

  actions: {
    setToken(token) {
      this.token = token
      this.state.token = token
      this.saveState()
    },
    
    setPermissions(permissions) {
      this.permissions = Array.isArray(permissions) ? permissions : []
      this.state.permissions = this.permissions
      
      this.saveState()
      
      this.generateRoutes()
    },

    setUtype(role) {
      console.warn('setUtype is deprecated, use setPermissions instead');
    },

    login(data) {
      this.state = data
      this.saveState()
    },

    logout() {
      // 清除所有状态
      this.state = {}
      this.token = ''
      this.permissions = []
      this.routes = []
      
      // 清除用户信息
      const userStore = useUserStore()
      userStore.clearUserInfo()  // 如果使用方案一
      // 或者直接重置用户信息
      // userStore.userInfo = {
      //   account: '',
      //   name: '',
      //   email: '',
      //   photo: '',
      //   signature: '',
      //   gameInfo: {
      //     nick: '',
      //     maxArenaWins: 0,
      //     curStage: 0,
      //     petMaxLev: 0,
      //     monKingWin: 0,
      //     taskIds: '',
      //     petAllNum: 0,
      //     messWin: 0
      //   }
      // }
      
      // 清除所有相关的localStorage项
      localStorage.removeItem('token')
      localStorage.removeItem('lastPath')
      localStorage.removeItem(LOCALSTORAGEKEY)
      localStorage.removeItem('seer_session') // 如果有其他会话相关信息也清除
      
      // 使用replace而不是push，防止历史记录堆积
      router.replace({ path: '/login', replace: true })
    },

    // 加载自动路由配置
    async loadAutoRoutes() {
      // 这里直接返回静态路由配置
      return routes
    },

    filterRoutes(routes) {
      const filterRoute = (route) => {
        // 确保每个路由都有 meta 属性
        route.meta = route.meta || {}

        // 子路由处理 - 先处理子路由
        if (route.children) {
          route.children = route.children.filter(filterRoute)
          
          // 如果有可见的子路由，父路由也要保留
          if (route.children.length > 0) {
            return true
          }
        }

        // 仅检查 permissions 字段
        if (route.meta?.permissions && route.meta.permissions.length > 0) {
          // 检查用户是否有路由所需的任一权限
          const hasPermission = route.meta.permissions.some(permission => 
            this.permissions.includes(permission)
          );
          
          if (!hasPermission) {
            return false;
          }
        }

        return true
      }

      return routes.filter(filterRoute)
    },

    async generateRoutes() {  
      const routes = await this.loadAutoRoutes();
      
      // 保存原始路由结构
      const originalRouteStructure = JSON.parse(JSON.stringify(routes));
      
      // 过滤路由
      this.routes = this.filterRoutes(routes);
      
      // 确保路由结构一致性
      if (this.routes.length > 0 && !this.routes[0].children && originalRouteStructure[0].children) {
        // 如果过滤后丢失了层级结构，重新构建
        this.routes = [
          {
            ...originalRouteStructure[0],
            children: this.routes
          }
        ];
      }
      
      // 移除可能已存在的路由
      this.routes.forEach(route => {
        if (router.hasRoute(route.name)) {
          router.removeRoute(route.name);
        }
      });
      
      // 添加过滤后的路由
      this.routes.forEach(route => {
        router.addRoute(route);
      });
      
      // 触发响应式更新
      this.routes = [...this.routes];
      
      
      return this.routes;
    },

    // 保存状态到 localStorage
    saveState() {
      // 保存完整状态，但不再包含 utype
      const stateToSave = {
        ...this.$state,
      };
      
      localStorage.setItem(LOCALSTORAGEKEY, JSON.stringify(stateToSave));
      console.log('保存状态到 localStorage:', stateToSave);
    }
  }
})
